/**
 * Copyright(c) 2010 Ceno Techonologies Co., Ltd.
 *
 * History:
 *   15-1-9 下午2:52 Created by lyyang
 */
package com.jade.bss.business.groupon.dianping;

import java.text.SimpleDateFormat;
import java.util.*;
import javax.annotation.PostConstruct;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jade.bss.base.BssException;
import com.jade.bss.business.groupon.Groupon;
import com.jade.bss.business.groupon.GrouponRestriction;
import com.jade.bss.business.groupon.GrouponWrap;
import com.jade.bss.business.groupon.Sniffer;
import com.jade.bss.business.groupon.dianping.pdu.Deal;
import com.jade.bss.business.groupon.dianping.pdu.Response;
import com.jade.bss.business.groupon.dianping.pdu.Restriction;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;


/**
 * 大众点评团购嗅探器
 *
 * @author <a href="mailto:lyyang@ceno.cn">lyyang</a>
 * @version 1.0 15-1-9 下午2:52
 */
public class DianpingSniffer
        extends Sniffer
{
    protected ObjectMapper objectMapper = new ObjectMapper();
    private String appKey = "910449070";
    private String appSecret = "d1efaefc272a4a609a9fc3c49ea99ee2";
    private String apiUrl = "http://api.dianping.com/v1/deal/get_deals_by_business_id";

    public static void main(String[] args)
    {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("city", "上海");
        map.put("region", "长宁区");
        map.put("category", "美食");
        map.put("limit", "3");
        map.put("page", "1");
        DianpingSniffer sniffer = new DianpingSniffer();
        sniffer.init();
        try {
            System.out.println(sniffer.find("1", "test", "上海", "1901623"));
        }
        catch (BssException e) {
            e.printStackTrace();

        }
    }

    @PostConstruct
    public void init()
    {
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    public String getAppKey()
    {
        return appKey;
    }

    public void setAppKey(String appKey)
    {
        this.appKey = appKey;
    }

    public String getAppSecret()
    {
        return appSecret;
    }

    public void setAppSecret(String appSecret)
    {
        this.appSecret = appSecret;
    }

    public String getApiUrl()
    {
        return apiUrl;
    }

    public void setApiUrl(String apiUrl)
    {
        this.apiUrl = apiUrl;
    }

    public List<Groupon> find(String ownerId, String ownerType, String city, String keyword)
            throws BssException
    {

        List<Groupon> groupons = new ArrayList<Groupon>();
        List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
        params.add(new BasicNameValuePair("city", city));
        params.add(new BasicNameValuePair("business_id", keyword));
        Map<String, String> map = new HashMap<String, String>();
        for (BasicNameValuePair param : params) {
            map.put(param.getName(), param.getValue());
        }
        String sign = getSign(map);
        params.add(new BasicNameValuePair("sign", sign));
        params.add(new BasicNameValuePair("appkey", appKey));

        //对参数编码
        String strParam = URLEncodedUtils.format(params, "UTF-8");
        HttpClient client = new DefaultHttpClient();
        HttpGet method = new HttpGet(apiUrl + "?" + strParam);
        Response r = null;
        try {
            HttpResponse response = client.execute(method);
            String json = EntityUtils.toString(response.getEntity());
            r = objectMapper.readValue(json, Response.class);
        }
        catch (Exception ex) {
            ex.printStackTrace();
            throw new BssException(ex.getMessage(), ex.getMessage(), ex);

        }
        if (r.isSuccess()) {
            List<Deal> deals = r.getDeals();
            if (deals != null && deals.size() > 0) {
                for (Deal deal : deals) {
                    groupons.add(unwrap(ownerId, ownerType, deal));
                }
            }
        }
        return groupons;

    }

    public Groupon unwrap(String ownerId, String ownerType, GrouponWrap wrap)
    {
        Deal deal = (Deal) wrap;
        Groupon groupon = new Groupon();
        groupon.setCategories(deal.getCategories());
        groupon.setChannel(getChannel());
        groupon.setCity(deal.getCity());
        groupon.setCommissionRatio(deal.getCommissionRatio());
        groupon.setCurrentPrice(deal.getCurrentPrice());
        groupon.setDescription(deal.getDescription());
        groupon.setDistance(deal.getDistance());
        groupon.setH5Url(deal.getDealH5Url());
        groupon.setGrouponId(deal.getId());
        groupon.setImageUrl(deal.getImageUrl());
        groupon.setListPrice(deal.getListPrice());
        groupon.setOwnerId(ownerId);
        groupon.setOwnerType(ownerType);
        groupon.setPublishDate(deal.getPublishDate());
        groupon.setPurchaseCount(deal.getPurchaseCount());
        groupon.setPurchaseDeadline(deal.getPurchaseDeadline());
        groupon.setRegions(deal.getRegions());
        groupon.setsImageUrl(deal.getsImageUrl());
        groupon.setTitle(deal.getTitle());
        groupon.setWebUrl(deal.getDealUrl());
        groupon.setPopular(deal.isPopular());
        groupon.setNotice(deal.getNotice());
        Restriction r = deal.getRestriction();
        if (r != null) {
            GrouponRestriction restriction = new GrouponRestriction();
            restriction.setRefundable(r.isRefundable());
            restriction.setReservation(r.isReservation());
            restriction.setSpecialTips(r.getSpecialTips());
            groupon.setRestriction(restriction);
        }
        groupon.setMoreImages(deal.getMoreImageUrls());
        groupon.setMoreSmallImages(deal.getMoreSmallImageUrls());
//        List<Business> businesses = deal.getBusinesses();
//        if (businesses!=null&&businesses.size()>0){
//            List<BranchShop> shops = new ArrayList<BranchShop>();
//            for (Business business:businesses){
//                BranchShop shop = new BranchShop();
//                shop.setCity(business.getCity());
//                shop.setH5Url(business.getH5Url());
//                shop.setId(business.getId());
//                shop.setName(business.getName());
//                shop.setWebUrl(business.getUrl());
//                shops.add(shop);
//            }
//            groupon.setBranchShops(shops);
//        }
        return groupon;
    }

    public String getSign(Map<String, String> paramMap)
    {
        StringBuilder stringBuilder = new StringBuilder();

        // 对参数名进行字典排序
        String[] keyArray = paramMap.keySet().toArray(new String[0]);
        Arrays.sort(keyArray);
        // 拼接有序的参数名-值串
        stringBuilder.append(appKey);
        for (String key : keyArray) {
            stringBuilder.append(key).append(paramMap.get(key));
        }
        String codes = stringBuilder.append(appSecret).toString();
        String sign = org.apache.commons.codec.digest.DigestUtils.shaHex(codes).toUpperCase();
        return sign;
    }
}
